package com.qx.chat.system.service;

import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qx.chat.system.dao.AbstractRepository;
import com.qx.chat.system.entity.Dept;
import com.qx.chat.system.entity.DeptUser;
import com.qx.chat.system.entity.User;

/**
 * TODO
 * @author cyf
 * @version TODO
 */
@Component
public class OrgServiceImpl implements OrgService{
	//@Autowired
	//private AbstractRepository<User> userDaoImpl;
	@Autowired
	private AbstractRepository<Dept> deptDaoImpl;
	@Autowired
	private AbstractRepository<DeptUser> deptUserDaoImpl;
	@Autowired
	private AbstractRepository<User> userDaoImpl;
	/**
	 * 查询全组织人员json数据
	 * @return
	 */
	public JSONArray findOrgTreeJsonData(){
		JSONArray arr = findChildDeptAndUser("0000");
		return arr;
	}
	/**
	 * 递归查部门和用户
	 * 用户存于缓存
	 * @param deptId
	 * @return
	 */
	private JSONArray findChildDeptAndUser(String deptId){
		JSONArray arr = new JSONArray();
		List<Dept> dList = deptDaoImpl.findList("pId", deptId);
		for (Iterator<Dept> iterator = dList.iterator(); iterator.hasNext();) {
			Dept dept = (Dept) iterator.next();
			JSONObject jo = new JSONObject();
			jo.put("id", dept.getId());
			jo.put("name", dept.getName());
			jo.put("pId", dept.getpId());
			jo.put("click", false);
			jo.put("isParent", true);
			JSONArray findChildDeptAndUser = findChildDeptAndUser(dept.getId());
			jo.put("children", findChildDeptAndUser);
			arr.add(jo);
		}
		List<DeptUser> duList = deptUserDaoImpl.findList("dept", deptId);
		for (Iterator<DeptUser> iterator = duList.iterator(); iterator.hasNext();) {
			DeptUser deptUser = (DeptUser) iterator.next();
			User user = deptUser.getUser();
			//过滤管理员
			if(user.getId()!="0000"&&!"0000".equals(user.getId())){
				JSONObject jo = new JSONObject();
				jo.put("id", user.getId());
				jo.put("loginName", user.getLoginName());
				jo.put("name", user.getNickname());
				jo.put("pId", deptId);
				jo.put("isParent", false);
				jo.put("status", user.getOnline());
				arr.add(jo);
			}
		}
		return arr;
	}
	/**
	 * 根据用户id查询用户是否在线
	 * @param userId
	 * @return
	 */
	public boolean isOnline(String userId){
		User user = userDaoImpl.findById(userId);
		if(user!=null){
			return user.getOnline()==1;
		}
		return false;
	}
}
